package com.kxf.androidtestdemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.kxf.androidtestdemo.activity.AChartEngineActivity;
import com.kxf.androidtestdemo.activity.AnimationActivity;
import com.kxf.androidtestdemo.activity.AutoPlayWebActivity;
import com.kxf.androidtestdemo.activity.BluetoothActivity;
import com.kxf.androidtestdemo.activity.CacheWebViewActivity;
import com.kxf.androidtestdemo.activity.ConstraintLayoutActivity;
import com.kxf.androidtestdemo.activity.CropImageActivity;
import com.kxf.androidtestdemo.activity.CustomViewActivity;
import com.kxf.androidtestdemo.activity.DexLoaderActivity;
import com.kxf.androidtestdemo.activity.ElecSignatureActivity;
import com.kxf.androidtestdemo.activity.EpicHookActivity;
import com.kxf.androidtestdemo.activity.FFmpegActivity;
import com.kxf.androidtestdemo.activity.GsonTestActivity;
import com.kxf.androidtestdemo.activity.HandleTest1Activity;
import com.kxf.androidtestdemo.activity.HandleTest2Activity;
import com.kxf.androidtestdemo.activity.HandleTestActivity;
import com.kxf.androidtestdemo.activity.HanoiActivity;
import com.kxf.androidtestdemo.activity.ImgBgActivity;
import com.kxf.androidtestdemo.activity.IntentServiceActivity;
import com.kxf.androidtestdemo.activity.JsTestActivity;
import com.kxf.androidtestdemo.activity.JsbridgeActivity;
import com.kxf.androidtestdemo.activity.KotlinTestActivity;
import com.kxf.androidtestdemo.activity.ListViewActivity;
import com.kxf.androidtestdemo.activity.MpAndroidChartTestActivity;
import com.kxf.androidtestdemo.activity.NestedScrollViewTestActivity;
import com.kxf.androidtestdemo.activity.NotificationActivity;
import com.kxf.androidtestdemo.activity.OkHttpActivity;
import com.kxf.androidtestdemo.activity.OutSideViewGroupActivity;
import com.kxf.androidtestdemo.activity.PlayVideoActivity;
import com.kxf.androidtestdemo.activity.RefreshLayoutActivity;
import com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity;
import com.kxf.androidtestdemo.activity.ScrollViewActivity;
import com.kxf.androidtestdemo.activity.ServiceTestActivity;
import com.kxf.androidtestdemo.activity.ShadowViewActivity;
import com.kxf.androidtestdemo.activity.SysSettingsActivity;
import com.kxf.androidtestdemo.activity.SystemSettingActivity;
import com.kxf.androidtestdemo.activity.TestRefreshLayoutActivity;
import com.kxf.androidtestdemo.activity.ThreadPoolActivity;
import com.kxf.androidtestdemo.activity.TouchEventActivity;
import com.kxf.androidtestdemo.activity.ViewPagerActivity;
import com.kxf.androidtestdemo.activity.ViewStubActivity;
import com.kxf.androidtestdemo.activity.WorkManagerTestActivity;
import com.kxf.androidtestdemo.bean.BtnParm;
import com.kxf.androidtestdemo.bean.PayWebResponse;
import com.kxf.hellojni.nativejni.SayHello;
import com.kxf.libraryaar.Test;
import com.kxf.utils.CommandUtil;
import com.kxf.utils.RSAUtil;
import com.kxf.utils.Util;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import rx.functions.Action1;

public class MainActivity extends AppCompatActivity {

    private LinearLayout ll_main = null;
    private Button ll_main_btn = null;
    private TextView tv_time;
    private BtnParm[] btnParms = new BtnParm[]{
            BtnParm.getDefStartAty(this, ViewStubActivity.class)
            , BtnParm.getDefStartAty(this, ConstraintLayoutActivity.class)
            , BtnParm.getDefStartAty(this, ScrollViewActivity.class)
            , BtnParm.getDefStartAty(this, ImgBgActivity.class)
            , BtnParm.getDefStartAty(this, ShadowViewActivity.class)
            , BtnParm.getDefStartAty(this, RefreshLayoutActivity.class)
            , BtnParm.getDefStartAty(this, TestRefreshLayoutActivity.class)
            , BtnParm.getDefStartAty(this, NestedScrollViewTestActivity.class)
            , BtnParm.getDefStartAty(this, BluetoothActivity.class)
            , BtnParm.getDefStartAty(this, MpAndroidChartTestActivity.class)
            , BtnParm.getDefStartAty(this, AChartEngineActivity.class)
            , BtnParm.getDefStartAty(this, ViewPagerActivity.class)
//            , BtnParm.getDefStartAty(this, RnTestActivity.class)
//            , BtnParm.getDefStartAty(this, MyReactActivity.class)
            , BtnParm.getDefStartAty(this, SysSettingsActivity.class)
            , BtnParm.getDefStartAty(this, WorkManagerTestActivity.class)
            , BtnParm.getDefStartAty(this, CropImageActivity.class)
            , BtnParm.getDefStartAty(this, SystemSettingActivity.class)
            , BtnParm.getDefStartAty(this, PlayVideoActivity.class)
            , BtnParm.getDefStartAty(this, FFmpegActivity.class)
            , BtnParm.getDefStartAty(this, RegisterForActivityResultActivity.class)
            , BtnParm.getDefStartAty(this, OutSideViewGroupActivity.class)
            , BtnParm.getDefStartAty(this, CacheWebViewActivity.class)
            , BtnParm.getDefStartAty(this, EpicHookActivity.class)
            , BtnParm.getDefStartAty(this, NotificationActivity.class)
            , BtnParm.getDefStartAty(this, DexLoaderActivity.class)
            , BtnParm.getDefStartAty(this, AutoPlayWebActivity.class)};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_time = findViewById(R.id.tv_time);
        tv_time.setText(BuildConfig.BUILD_TIME_FORMAT);

        ll_main = findViewById(R.id.ll_main);
        ll_main_btn = findViewById(R.id.ll_main_btn);
        for (BtnParm btnParm : btnParms) {
            addBtn(btnParm);
        }

        Log.i("MainActivity", "SayHello.getHello() " + SayHello.getHello());

        //性能优化：过度绘制，DecorView的background此时对我们来说是无用的，
        //去掉window的背景可以在onCreate()中setContentView()之后调用
        getWindow().setBackgroundDrawable(null);

        Log.i("MainActivity", "onCreate " + Test.getClsName());
        getPermissions();

        testData();

        Log.i("MainActivity", "FILE_CONFIGS_KEY== " + BuildConfig.FILE_CONFIGS_KEY);

        new Thread(new Runnable() {
            @Override
            public void run() {

                doRoot();
            }
        }).start();

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                throw new NullPointerException("NullPointerException");
//            }
//        }).start();
    }

    private void doRoot(){
        Log.i("MainActivity", "CommandUtil.checkSuFile== " + CommandUtil.checkSuFile());
        File flie = CommandUtil.checkRootFile();
        Log.i("MainActivity", "CommandUtil.checkRootFile== " + flie);

        boolean re = CommandUtil.RootCommand("ls", flie==null?null:flie.getPath());
        Log.i("MainActivity", "CommandUtil.RootCommand== " + re);
    }

    private void testData(){
        /*
* RESULT_OK 返回第三方交易数据 ：Bundle[{msg_tp=0210, pay_tp=0, totalNum=null, totalPage=null, card_org=00 境内借记卡, amt=127432.00, data=null,
* refernumber=120610884037, batchbillno=null, card_no=621485|7756, adddataword=null, time_stamp=20191206162854, order_no=92dc9e8a-5301-4b7b-9e65-95c3da7cdadd,
* txndetail={"merid":"822588070130365","termid":"51262867","batchno":"000002","systraceno":"000192","authcode":"000000"}}]

RESULT_OK 返回第三方交易数据 ：Bundle[{msg_tp=0210, pay_tp=0, totalNum=null, totalPage=null, card_org=00 境内借记卡, amt=127432.00, data=null,
refernumber=120610874752, batchbillno=null, card_no=622202|7708, adddataword=null, time_stamp=20191206162319, order_no=f8bf0704-90d1-4951-96ac-07715c448e13,
txndetail={"merid":"822588070130365","termid":"51262864","batchno":"000005","systraceno":"000224","authcode":"012345"}}]
* */
        Bundle bundle = new Bundle();
        bundle.putString("msg_tp", "0210");
        bundle.putString("pay_tp", "0");
        bundle.putString("totalNum", null);
        bundle.putString("totalPage", null);
        bundle.putString("card_org", "00 境内借记卡");
        bundle.putString("amt", "127432.00");
        bundle.putString("refernumber", "120610874752");
        bundle.putString("card_no", "622202|7708");
        bundle.putString("adddataword", null);
        bundle.putString("time_stamp", "20191206162319");
        bundle.putString("order_no", "f8bf0704-90d1-4951-96ac-07715c448e13");
        bundle.putString("txndetail", "{\"merid\":\"822588070130365\",\"termid\":\"51262864\",\"batchno\":\"000005\",\"systraceno\":\"000224\",\"authcode\":\"012345\"}");
        Log.i("MainActivity", "bundle=" + bundle);

        PayWebResponse webResponse = new PayWebResponse();
        webResponse.setMsg_tp(bundle.getString("msg_tp"));
        webResponse.setPay_tp(bundle.getString("pay_tp"));
        webResponse.setRefernumber(bundle.getString("refernumber"));
        webResponse.setOrder_no(bundle.getString("order_no"));
        webResponse.setTime_stamp(bundle.getString("time_stamp"));
        webResponse.setReason(bundle.getString("reason"));
        webResponse.setAdddataword(bundle.getString("adddataword"));
        webResponse.setTxndetail(bundle.getString("txndetail"));
        webResponse.setCard_org(bundle.getString("card_org"));
        webResponse.setBatchbillno(bundle.getString("batchbillno"));
        webResponse.setRemarkinfo(bundle.getString("remarkinfo"));
        webResponse.setAmt(bundle.getString("amt"));
        webResponse.setMsg_code("0");

        String webData = new Gson().toJson(webResponse);
        Log.i("MainActivity", "webData=" + webData);

        try {
            RSAUtil.initKey(2048);
//            throw new Error("测试抛出error");
//            return;
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            Log.d("kxf", "finally======" );
        }
        Log.d("kxf", "finally next======" );

        Log.d("kxf", "isExistSDCard=" + isExistSDCard());
//        startService(new Intent(this, MyRemoteService.class));
    }

    private void addBtn(BtnParm btnParm) {
        Button btn = new Button(this);
        btn.setLayoutParams(ll_main_btn.getLayoutParams());
        btn.setText(btnParm.btnText);
        btn.setOnClickListener(btnParm.l);
        ll_main.addView(btn, 0);
    }

    private static boolean isExistSDCard() {
        Log.d("kxf", "Environment.getExternalStorageState()=" + Environment.getExternalStorageState());
        Log.d("kxf", "Environment.MEDIA_MOUNTED=" + Environment.MEDIA_MOUNTED);
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    protected void getPermissions() {
        Log.d("kxf", "分别申请多个权限========>");
        //分别申请多个权限
        RxPermissions.getInstance(MainActivity.this)
                //分别申请多个权限时，使用requestEach
                .requestEach(Manifest.permission.INTERNET,Manifest.permission.WRITE_SETTINGS,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Log.d("MainActivity", "permission=" + permission);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("MainActivity", "onResume  System.gc()");
        System.gc();
    }

    public void onClick(View view) {
        startActivity(new Intent(this, AnimationActivity.class));
    }

    public void onCvClick(View view) {
        startActivity(new Intent(this, CustomViewActivity.class));
    }

    public void onServiceTestClick(View view) {
        startActivity(new Intent(this, ServiceTestActivity.class));
    }

    public void onKotlinTest(View view) {
        startActivity(new Intent(this, KotlinTestActivity.class));
    }

    public void onThreadPoolTest(View view) {
        startActivity(new Intent(this, ThreadPoolActivity.class));
    }

    public void onGsonTest(View view) {
        startActivity(new Intent(this, GsonTestActivity.class));
    }

    public void onHanoiActivity(View view) {
        startActivity(new Intent(this, HanoiActivity.class));
    }

    public void onHandleTestActivity(View view) {
        startActivity(new Intent(this, HandleTestActivity.class));
    }

    public void onHandleTest1Activity(View view) {
        startActivity(new Intent(this, HandleTest1Activity.class));
    }

    public void onHandleTest2Activity(View view) {
        startActivity(new Intent(this, HandleTest2Activity.class));
    }

    public void onJsTestActivity(View view) {
        startActivity(new Intent(this, JsTestActivity.class));
    }

    public void onOkHttpActivity(View view) {
        startActivity(new Intent(this, OkHttpActivity.class));
    }

    public void onScrollTextViewActivity(View view) {

        Map<String, String> p = new TreeMap<>();
        p.put("appId", "com.lkl.pay");
        p.put("nonceStr", "12345678123456781234567812345678");
//        p.put("sign", "");
        p.put("transType", "000000");
        p.put("amount", "100.12");
        p.put("inCardNo", "6200000000000000002");
        p.put("inId", "330012199211116666");
        p.put("orderId", "202004101412");
        p.put("outCardNo", "6200000000000000001");
        Log.i("MainActivity", "onScrollTextViewActivity p=" + p);

        String url = "";
        String signSrc = "";
        Set<String> keySet = p.keySet();
        for (String key : keySet) {
            signSrc = signSrc + key + "=" + p.get(key) + "&";
        }
        if (signSrc.length() > 0) {
            signSrc = signSrc.substring(0, signSrc.length() - 1);
        }
        Log.i("MainActivity", "onScrollTextViewActivity signSrc=" + signSrc);
        String sign = Base64.encodeToString(RSAUtil.sign(signSrc.getBytes()), Base64.URL_SAFE | Base64.NO_WRAP);
        Log.i("MainActivity", "onScrollTextViewActivity sign=" + sign);
        boolean b = RSAUtil.verify(signSrc.getBytes(), Base64.decode(sign, Base64.URL_SAFE | Base64.NO_WRAP));
        Log.i("MainActivity", "onScrollTextViewActivity b=" + b);
        url = "http://androidtestdemo:8080/views?" + signSrc + "&sign=" + sign;
//        url = "http://lakala_large_account:8080/TransferAccounts?" + signSrc + "&sign=" + sign;

        Log.i("MainActivity", "onScrollTextViewActivity url=" + url);
        Uri uri = Uri.parse(url);
        if (hasApplication(uri)) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            action.setData(uri);
            startActivityForResult(action, 1002);//1002可以自行定义，和onActivityResult中保持一致
        }
    }

    /**
     * 判断是否安装了应用
     *
     * @return true 为已经安装
     */
    private boolean hasApplication(Uri uri) {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(uri);
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        Log.i("MainActivity", "hasApplication list=" + list);
        return list != null && list.size() > 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("MainActivity", "onActivityResult requestCode=" + requestCode);
        Log.i("MainActivity", "onActivityResult resultCode=" + resultCode);
        Log.i("MainActivity", "onActivityResult data=" + Util.getIntentExtrasToString(data));
        if (requestCode == 1002) {
            if (RESULT_OK == resultCode) {
                //交易成功
                Toast.makeText(this, "大额交易成功", Toast.LENGTH_SHORT).show();
            } else if (RESULT_CANCELED == resultCode) {
                //交易取消
                Toast.makeText(this, "大额交易取消", Toast.LENGTH_SHORT).show();
            } else if (-2 == resultCode) {
                //交易失败
                String errorCode = data.getStringExtra("errorCode");//错误码
                String errorMsg = data.getStringExtra("errorMsg");//错误信息
                Toast.makeText(this, "大额交易失败：" + errorCode + " " + errorMsg, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void onIntentServiceActivity(View view) {
        startActivity(new Intent(this, IntentServiceActivity.class));
    }

    public void onSchemaTest(View view) {
        Map<String, String> p = new TreeMap<>();
        p.put("appId", "com.lkl.pay");
        p.put("nonceStr", "12345678123456781234567812345678");
//        p.put("sign", "");
        p.put("transType", "000000");
        p.put("amount", "100.12");
        p.put("inCardNo", "6200000000000000002");
        p.put("inId", "330012199211116666");
        p.put("orderId", "202004101412");
        p.put("outCardNo", "6200000000000000001");
        Log.i("MainActivity", "onSchemaTest p=" + p);

        String url = "";
        String signSrc = "";
        Set<String> keySet = p.keySet();
        for (String key : keySet) {
            signSrc = signSrc + key + "=" + p.get(key) + "&";
        }
        if (signSrc.length() > 0) {
            signSrc = signSrc.substring(0, signSrc.length() - 1);
        }
        Log.i("MainActivity", "onSchemaTest signSrc=" + signSrc);
        String sign = Base64.encodeToString(RSAUtil.sign(signSrc.getBytes()), Base64.URL_SAFE | Base64.NO_WRAP);
        Log.i("MainActivity", "onSchemaTest sign=" + sign);
        boolean b = RSAUtil.verify(signSrc.getBytes(), Base64.decode(sign, Base64.URL_SAFE | Base64.NO_WRAP));
        Log.i("MainActivity", "onSchemaTest b=" + b);
        url = "http://androidtestdemo:8080/views?" + signSrc + "&sign=" + sign;

        Log.i("MainActivity", "onSchemaTest url=" + url);
        Uri uri = Uri.parse(url);
        if (hasApplication(uri)) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            action.setData(uri);
            startActivityForResult(action, 1003);
        }
    }

    private Intent getCallIntent() {
        Intent intent = new Intent("lakala.intent.action.LARGE_ACCOUNT");
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        Log.i("MainActivity", "onSchemaTest resolveInfos=" + resolveInfos);
        if (null != resolveInfos && resolveInfos.size() > 0) {
            ComponentName component = new ComponentName(resolveInfos.get(0).activityInfo.packageName, resolveInfos.get(0).activityInfo.name);
            intent.setComponent(component);
            return intent;
        } else {
            return null;
        }
    }

    public void onElecSignature(View view) {
        startActivity(new Intent(this, ElecSignatureActivity.class));
    }

    public void onJsbridge(View view) {
        startActivity(new Intent(this, JsbridgeActivity.class));
    }

    public void onListViewActivity(View view) {
        startActivity(new Intent(this, ListViewActivity.class));
    }

    public void onTouchEventActivity(View view) {
        startActivity(new Intent(this, TouchEventActivity.class));
    }

}
